package com.basic.library.utils.download

import android.util.Log
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.SpeedCalculator
import com.liulishuo.okdownload.core.Util
import com.liulishuo.okdownload.core.breakpoint.BlockInfo
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo
import com.liulishuo.okdownload.core.cause.EndCause
import com.liulishuo.okdownload.core.listener.DownloadListener4WithSpeed
import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend.Listener4SpeedModel

/**
 * @author yj
 * @description
 */
class MDownloadListener4WithSpeed(private val callback: DownLoadCallBack?) : DownloadListener4WithSpeed() {
    private val downloadTag = "Download";
    private var totalLength: Long = 0
    private var readableTotalLength: String? = null
    override fun taskStart(task: DownloadTask) {
        Log.i(downloadTag, "【任务启动】" + task.url)
        callback?.taskStart()
    }

    override fun connectStart(task: DownloadTask, blockIndex: Int, requestHeaderFields: Map<String, List<String>>) {

    }

    override fun connectEnd(task: DownloadTask, blockIndex: Int, responseCode: Int, responseHeaderFields: Map<String, List<String>>) {

    }

    override fun infoReady(task: DownloadTask, info: BreakpointInfo, fromBreakpoint: Boolean, model: Listener4SpeedModel) {
        totalLength = info.totalLength
        readableTotalLength = Util.humanReadableBytes(totalLength, true)
        Log.i(downloadTag, "【初始进度】" + info.totalOffset.toFloat() / totalLength * 100 + "%" + "，" + info.toString())
    }

    override fun progressBlock(task: DownloadTask, blockIndex: Int, currentBlockOffset: Long, blockSpeed: SpeedCalculator) {

    }

    override fun progress(task: DownloadTask, currentOffset: Long, taskSpeed: SpeedCalculator) {
        val readableOffset = Util.humanReadableBytes(currentOffset, true)
        val progressStatus = "$readableOffset/$readableTotalLength"
        val speed = taskSpeed.speed()
        val percent = currentOffset.toFloat() / totalLength * 100
        Log.i(downloadTag, "【下载进度】$currentOffset[$progressStatus]，速度：$speed，进度：$percent%")
        callback?.progress(percent)
    }

    override fun blockEnd(task: DownloadTask, blockIndex: Int, info: BlockInfo, blockSpeed: SpeedCalculator) {

    }

    override fun taskEnd(task: DownloadTask, cause: EndCause, realCause: Exception?, taskSpeed: SpeedCalculator) {
        Log.i(downloadTag, "【任务完成】" + cause.name + "：" + if (realCause != null) realCause.message else "无异常")
        if (cause == EndCause.COMPLETED)
            callback?.taskSuccess(task)
        else
            callback?.taskFail(task, cause, realCause)
    }

}